package com.sxfq.loansupermarket.backsystem.modular.weixin.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.GunsApplication;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.SearchCustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.DoctorInfo;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.TcInfo;
import com.sxfq.loansupermarket.backsystem.modular.basicData.service.IGetListService;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.ConsultantInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.DepartmentInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * 微信开发者接入
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/receptionPatientsCentral")
public class ReceptionPatientsCentralController extends BaseController {
    private String PREFIX = "/weixin/app/";

    protected final static Logger logger = LoggerFactory.getLogger(GunsApplication.class);

    @Autowired
    private SqlMapper sqlMapper;
    @Autowired
    ICustomerService receptionService;
    @Autowired
    IGetListService getListService;


    /**
     * 到店患者列表加载
     */
    @RequestMapping(value = "/getReceptionPatient", method = RequestMethod.POST)
    @ResponseBody
    public List<CustomerInfo> getReceptionPatient(String startArrivalTime, String endArrivalTime, String sreach) {
        SearchCustomerInfo info=new SearchCustomerInfo();
        Page<CustomerInfo> page = new Page<>();
        info.setStartIndex(0);
        info.setLimitIndex(50);
        info.setStartArrivalTime(startArrivalTime);
        info.setEndArrivalTime(endArrivalTime);
        info.setSreach(sreach);
        page.setCurrent(0);
        page.setSize(50);
        List<CustomerInfo> list = receptionService.selectPageListByQueryGetMap2(page, info);
        return list;
    }

    /**
     * APP - 到店
     * 点击患者跳转页面 - 详情
     */
    @RequestMapping("/getReceptionPatient_details/{customerId}")
    public String getReceptionPatient_details(@PathVariable String customerId,Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql="select (CASE a.customer_sex " +
                " WHEN 1 THEN " +
                "  '男' " +
                "  WHEN 2 THEN " +
                "  '女' " +
                "  ELSE " +
                "  '未知' " +
                "  END " +
                "  ) as sex ," +
                "( " +
                " CASE a.customer_sex " +
                " WHEN 1 THEN " +
                " 'https://pynnn.oss-cn-hangzhou.aliyuncs.com/weixin-img/app/portrait01.png' " +
                " WHEN 2 THEN " +
                " 'https://pynnn.oss-cn-hangzhou.aliyuncs.com/weixin-img/app/portrait02.png' " +
                " ELSE " +
                " 'https://pynnn.oss-cn-hangzhou.aliyuncs.com/weixin-img/app/portrait03.png' " +
                " END " +
                ") as avatar ,"+
                "a.* from "+ShiroKit.getUser().getCustomer_info()+" a where id ='"+customerId+"'";
        ReservationsInfo info=sqlMapper.selectOne(sql,ReservationsInfo.class);
        model.addAttribute("info",info);
        return PREFIX + "reception/patient/patient_details.html";
    }

    /**
     * APP - 前台预约视图
     */
    @RequestMapping("/appointment_index")
    public String appointment_index(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getDoctorInfoList() == null) {
            String doctorListSql = " select a.id as id,a.account as doctor from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on find_in_set(c.id,a.roleid) > 0 " +
                    " where b.abbreviation='" + ShiroKit.getUser().getAbbreviation() + "' and (c.name='医生' or c.name='洁牙师') and a.status='1';";
            List<DoctorInfo> doctorInfoList = sqlMapper.selectList(doctorListSql, DoctorInfo.class);
            ShiroKit.getUser().setDoctorInfoList(doctorInfoList);
        }
        model.addAttribute("doctorList", ShiroKit.getUser().getDoctorInfoList());
        return PREFIX + "reception/appointment/appointment_index.html";
    }

    /**
     * APP - 前台预约视图
     */
    @RequestMapping(value = "/getDataListApp",method = RequestMethod.POST)
    @ResponseBody
    public List<ConsultantInfo> getDataListApp(String doctor,String timeValue,Model model) {
        String sql = " select * from (select t1.id as id,t.customer_name as customerName,customer_status as customerStatus,t.check_status as checkStatus,t.customer_age as customerAge,t.customer_phone as customerPhone,t.medical_record_number as medicalRecordNumber," +
                " ( " +
                " CASE t.customer_sex " +
                " WHEN 1 THEN " +
                "     '男' " +
                " WHEN 2 THEN " +
                "     '女' " +
                " ELSE " +
                "     '未知' " +
                " END " +
                "    ) as sex ,t.archiving as archiving ,t.reservations_id as reservationsId,t.yellow_number as yellowNumber," +
                "t.treatment_unit as treatmentUnit,t.account_arrears as accountArrears," +
                "(select count(id) from " + ShiroKit.getUser().getCustomer_info() + " b where t.reservations_id=b.reservations_id and left(start_time,10)=left(now(),10)) as todaySum," +
                "(select count(id) from " + ShiroKit.getUser().getCustomer_info() + " b where t.reservations_id=b.reservations_id and left(start_time,10)>left(now(),10)) as aftersSum," +
                "(select count(id) from " + ShiroKit.getUser().getCustomer_info() + " b where t.reservations_id=b.reservations_id and left(start_time,10)<left(now(),10)) as beforeSum," +
                "t.arrival_status as arrivalStatus,t.arrival_store as arrivalStore ,t.birthday as birthday ," +
                "left(t.create_appointment_time,19) as createAppointmentTime,t.remarks as remarks,t.remarks_reservation as remarksReservation, t.field_tc as fieldTc,t.first_visit_date as firstVisitDate," +
                "t.appointment_pay_service as appointmentPayService ,t.start_time as startTime, t.end_time as endTime,t.doctor,t.id as customerId from " + ShiroKit.getUser().getCustomer_info() + " t " +
                "left join user t1 on t.doctor=t1.account " +
                "where left(t.start_time,10)='"+timeValue+"' and doctor='"+doctor+"' and t.arrival_status!=8 order by t.create_appointment_time) t2 ";
        List<ConsultantInfo> DataList = sqlMapper.selectList(sql, ConsultantInfo.class);
        return DataList;
    }

    /**
     * APP - 前台预约视图
     */
    @RequestMapping("/appointment_add")
    public String appointment_add(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getSessionAttr("outpatientManagementList") == null) {
            List<Map<String, Object>> outpatientManagementList = getListService.outpatientManagementList();
            ShiroKit.setSessionAttr("outpatientManagementList", outpatientManagementList);
        }
        model.addAttribute("outpatientManagementList", ShiroKit.getSessionAttr("outpatientManagementList"));
        if (ShiroKit.getUser().getDoctorInfoList() == null) {
            String doctorListSql = " select a.id as id,a.account as doctor from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on find_in_set(c.id,a.roleid) > 0 " +
                    " where b.abbreviation='" + ShiroKit.getUser().getAbbreviation() + "' and (c.name='医生' or c.name='洁牙师') and a.status='1';";
            List<DoctorInfo> doctorInfoList = sqlMapper.selectList(doctorListSql, DoctorInfo.class);
            ShiroKit.getUser().setDoctorInfoList(doctorInfoList);
        }
        model.addAttribute("doctorList", ShiroKit.getUser().getDoctorInfoList());
        if (ShiroKit.getUser().getDepartmentList() == null) {
            String getListSql = "select a.department as department from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.is_upper=1 group by a.department order by a.id;";
            List<DepartmentInfo> departmentList=sqlMapper.selectList(getListSql,DepartmentInfo.class);
            ShiroKit.getUser().setDepartmentList(departmentList);
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        if (ShiroKit.getSessionAttr("projectNameList") == null) {
            String selectSql = "select id,add_name as addName,project_category as projectCategory,project_name as projectName ," +
                    "create_time as createTime,update_time as updateTime from diagnose_project_info;";
            ShiroKit.setSessionAttr("projectNameList", sqlMapper.selectList(selectSql));
        }
        model.addAttribute("departmentList",ShiroKit.getUser().getDepartmentList());
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("projectNameList", ShiroKit.getSessionAttr("projectNameList"));
        return PREFIX + "reception/appointment/appointment_add.html";
    }

    /**
     * APP - 搜索患者页面
     */
    @RequestMapping("/appointment_selectPatients")
    public String appointment_selectPatients(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "reception/appointment/appointment_selectPatients.html";
    }

    /**
     * 搜索预约患者
     */
    @RequestMapping(value = "/getAppointmentSelectPatients", method = RequestMethod.POST)
    @ResponseBody
    public List<CustomerInfo> getAppointmentSelectPatients(String reach) {
        String sql2 = " ";
        if (StringUtils.isNotBlank(reach)) {
            sql2 = "  and (t.customer_name like CONCAT('%','" + reach + "','%') or t.customer_phone like CONCAT('%','" + reach + "','%') " +
                    "  or t.customer_phone2 like CONCAT('%','" + reach + "','%') or " +
                    "  t.medical_record_number like CONCAT('%','" + reach + "','%')" +
                    " or t.szm like CONCAT('%','" + reach + "','%'))";
        }
        String sql = "select * from (select " +
                "(" +
                " CASE t.customer_sex " +
                " WHEN 1 THEN " +
                " '男' " +
                " WHEN 2 THEN " +
                " '女' " +
                " ELSE " +
                " '未知' " +
                " END " +
                " ) as sex ,t.reservations_id as reservationsId, t.id,t.customer_name as customerName,t.customer_age as customerAge," +
                "t.customer_phone as customerPhone,t.customer_phone2 as customerPhone2,t.arrival_store as arrivalStore,t.phone_shar_ship as phoneSharShip," +
                "t.account_arrears as accountArrears,t.medical_record_number as medicalRecordNumber," +
                "t.one_channel as oneChannel,t.two_channel as twoChannel,t.thr_channel as thrChannel,'dd' as scordd " +
                " from " + ShiroKit.getUser().getCustomer_info() + " t " +
                " where 1=1 " + sql2 + " and arrival_status!=8 and arrival_status!=1 and arrival_status!=6 and arrival_status!=7 and arrival_status!=9 and arrival_status!=10 " +
                " and arrival_time is not null order by arrival_time desc ) t2 group by t2.reservationsId" +
                " limit 0,20";
        List<CustomerInfo> customerInfoList = sqlMapper.selectList(sql, CustomerInfo.class);
        if (customerInfoList.size() == 0) {//本店查不到，查市场约的患者
            if (StringUtils.isNotBlank(reach)) {
                sql2 = "  and t.search_field like CONCAT('%','" + reach + "','%') ";
            }
            String sqlsc = "select * from (select " +
                    "       ( " +
                    "        CASE t.customer_sex " +
                    "        WHEN 1 THEN " +
                    "        '男' " +
                    "        WHEN 2 THEN " +
                    "        '女' " +
                    "        ELSE " +
                    "        '未知' " +
                    "        END " +
                    "        ) as sex , t.id as reservationsId,t.customer_name as customerName," +
                    "t.one_channel as oneChannel,t.two_channel as twoChannel,t.thr_channel as thrChannel," +
                    "t.department as department,t.customer_age as customerAge,t.first_visit_date as firstVisitDate," +
                    "t.customer_phone as customerPhone,t.customer_phone2 as customerPhone2,t.status,t.arrival_store as arrivalStore," +
                    "t.phone_shar_ship as phoneSharShip,'sc' as scordd " +
                    " from reservations_info t " +
                    " where 1=1 " + sql2 + " ) t2 group by t2.reservationsId order by t2.firstVisitDate " +
                    " limit 0,20";
            customerInfoList = sqlMapper.selectList(sqlsc, CustomerInfo.class);
        }
        return customerInfoList;
    }

    /**
     * 点击患者-到店患者回显
     */
    @RequestMapping(value = "/getCustomerByReservationsIdApp/{reservationsId}")
    public String getCustomerByReservationsId(@PathVariable String reservationsId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sqlcu = "select " +
                " (" +
                " CASE t.customer_sex " +
                " WHEN 1 THEN " +
                "     '男' " +
                " WHEN 2 THEN " +
                "     '女' " +
                " ELSE " +
                "     '未知' " +
                " END " +
                " ) as sex,t.id as customerId,t.* from " + ShiroKit.getUser().getCustomer_info() + " t " +
                " where t.reservations_id='" + reservationsId + "' and t.arrival_time is not null order by t.arrival_time limit 0,1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sqlcu, CustomerInfo.class);
        if (ShiroKit.getSessionAttr("outpatientManagementList") == null) {
            List<Map<String, Object>> outpatientManagementList = getListService.outpatientManagementList();
            ShiroKit.setSessionAttr("outpatientManagementList", outpatientManagementList);
        }
        model.addAttribute("outpatientManagementList", ShiroKit.getSessionAttr("outpatientManagementList"));
        if (ShiroKit.getUser().getDoctorInfoList() == null) {
            String doctorListSql = " select a.id as id,a.account as doctor from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on find_in_set(c.id,a.roleid) > 0 " +
                    " where b.abbreviation='" + ShiroKit.getUser().getAbbreviation() + "' and (c.name='医生' or c.name='洁牙师') and a.status='1';";
            List<DoctorInfo> doctorInfoList = sqlMapper.selectList(doctorListSql, DoctorInfo.class);
            ShiroKit.getUser().setDoctorInfoList(doctorInfoList);
        }
        model.addAttribute("doctorList", ShiroKit.getUser().getDoctorInfoList());
        if (ShiroKit.getUser().getDepartmentList() == null) {
            String getListSql = "select a.department as department from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.is_upper=1 group by a.department order by a.id;";
            List<DepartmentInfo> departmentList=sqlMapper.selectList(getListSql,DepartmentInfo.class);
            ShiroKit.getUser().setDepartmentList(departmentList);
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        if (ShiroKit.getSessionAttr("projectNameList") == null) {
            String selectSql = "select id,add_name as addName,project_category as projectCategory,project_name as projectName ," +
                    "create_time as createTime,update_time as updateTime from diagnose_project_info;";
            ShiroKit.setSessionAttr("projectNameList", sqlMapper.selectList(selectSql));
        }
        model.addAttribute("departmentList",ShiroKit.getUser().getDepartmentList());
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("projectNameList", ShiroKit.getSessionAttr("projectNameList"));
        customerInfo.setScordd("dd");
        model.addAttribute("customerInfo", customerInfo);
        return PREFIX + "reception/appointment/appointment_addTwo.html";
    }

    /**
     * 点击患者-市场患者回显
     */
    @RequestMapping(value = "/getReservationsByReservationsIdApp/{reservationsId}" )
    public String getReservationsByReservationsId(@PathVariable String reservationsId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sqlre = "select " +
                " ( " +
                " CASE t.customer_sex " +
                " WHEN 1 THEN " +
                "     '男' " +
                " WHEN 2 THEN " +
                "     '女' " +
                " ELSE " +
                "     '未知' " +
                " END " +
                " ) as sex,t.id as reservationsId,'' as customerId,t.* from reservations_info t " +
                " where t.id='" + reservationsId + "' limit 0,1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sqlre, CustomerInfo.class);
        if (ShiroKit.getSessionAttr("outpatientManagementList") == null) {
            List<Map<String, Object>> outpatientManagementList = getListService.outpatientManagementList();
            ShiroKit.setSessionAttr("outpatientManagementList", outpatientManagementList);
        }
        model.addAttribute("outpatientManagementList", ShiroKit.getSessionAttr("outpatientManagementList"));
        if (ShiroKit.getUser().getDoctorInfoList() == null) {
            String doctorListSql = " select a.id as id,a.account as doctor from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on find_in_set(c.id,a.roleid) > 0 " +
                    " where b.abbreviation='" + ShiroKit.getUser().getAbbreviation() + "' and (c.name='医生' or c.name='洁牙师') and a.status='1';";
            List<DoctorInfo> doctorInfoList = sqlMapper.selectList(doctorListSql, DoctorInfo.class);
            ShiroKit.getUser().setDoctorInfoList(doctorInfoList);
        }
        model.addAttribute("doctorList", ShiroKit.getUser().getDoctorInfoList());
        if (ShiroKit.getUser().getDepartmentList() == null) {
            String getListSql = "select a.department as department from " + ShiroKit.getUser().getPay_service_grade_info() + " a where a.is_upper=1 group by a.department order by a.id;";
            List<DepartmentInfo> departmentList=sqlMapper.selectList(getListSql,DepartmentInfo.class);
            ShiroKit.getUser().setDepartmentList(departmentList);
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        if (ShiroKit.getSessionAttr("projectNameList") == null) {
            String selectSql = "select id,add_name as addName,project_category as projectCategory,project_name as projectName ," +
                    "create_time as createTime,update_time as updateTime from diagnose_project_info;";
            ShiroKit.setSessionAttr("projectNameList", sqlMapper.selectList(selectSql));
        }
        model.addAttribute("departmentList",ShiroKit.getUser().getDepartmentList());
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("projectNameList", ShiroKit.getSessionAttr("projectNameList"));
        customerInfo.setScordd("sc");
        model.addAttribute("customerInfo", customerInfo);
        return PREFIX + "reception/appointment/appointment_addTwo.html";
    }

}